<template>
  <div>
    <div class="marginT20">
      <el-row :gutter="20">
        <el-col v-for="(item, index) in listData" :key="index" :span="8">
          <div v-if="item && item.length > 0" class="marginT20 pa10 border-default">
            <ul class="tags-box">
              <li
                v-for="(tag, inx) in item"
                :key="inx"
                class="tags-item"
                :class="selectArr[index] === inx ? 'active' : ''"
              >
                <div
                  class="name text-ellipsis-1"
                  @click="switchTag(index, tag, inx)"
                >{{ tag.tagsName }}</div>
                <div v-if="tag.tagsName " class="text-box">
                  <el-button type="text" @click="addOrEdit(index, tag, inx)">修改</el-button>
                  <el-button type="text" @click="copyOrMerge(index, tag, inx)">复制</el-button>
                  <el-button type="text" @click="delect(index, tag, inx)">删除</el-button>
                </div>
              </li>
            </ul>
            <div class="marginT20 btn-box">
              <el-button type="primary" @click="addOrEdit(index)">添加</el-button>
              <el-button type="primary" @click="copyOrMerge(index)">合并</el-button>
            </div>
          </div>
          <div v-else class="marginT20 pa10 border-default">
            <ul class="tags-box">
              <li />
            </ul>
            <div class="marginT20 btn-box">
              <el-button type="primary" @click="addOrEdit(index)">添加</el-button>
              <el-button type="primary" @click="copyOrMerge(index)">合并</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!--  修改与添加  -->
    <el-dialog :close-on-click-modal="false" :visible.sync="addOrEditDialog.visible">
      <el-form :model="addOrEditDialog">
        <el-form-item :label="addOrEditDialog.title">
          <el-input v-model="addOrEditDialog.tagsName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOrEditDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEditSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--  复制与合并  -->
    <el-dialog
      :close-on-click-modal="false"
      :title="copyOrMergeDialog.title"
      :visible.sync="copyOrMergeDialog.visible"
      width="80%"
    >
      <div style="margin: 20px 0 0;" class="content">
        <el-row :gutter="20">
          <el-col v-for="(item, index) in listData" :key="index" :span="8">
            <div v-if="item && item.length > 0" class="marginT20 pa10 border-default">
              <el-checkbox-group
                v-model="checkedTags"
                :max="copyOrMergeDialog.isCopy ? 1 : 2"
                @change="val => {return tagsChange(val, index)}"
              >
                <el-checkbox
                  v-if="copyOrMergeDialog.isCopy"
                  label="0"
                  style="position: absolute; transform: translate(-10px,-58px);"
                >根目录</el-checkbox>
                <ul class="tags-box">
                  <li
                    v-for="(tag, inx) in item"
                    :key="inx"
                    class="tags-item"
                    :class="selectArr[index] === inx ? 'active' : ''"
                  >
                    <div class="checkbox text-ellipsis-1">
                      <el-checkbox :label="tag.tagsId">{{ tag.tagsName }}</el-checkbox>
                    </div>
                    <div
                      class="name text-ellipsis-1"
                      @click="switchTag(index, tag, inx)"
                    >{{ tag.tagsName }}</div>
                  </li>
                </ul>
              </el-checkbox-group>
              <!-- <div class="marginT20 btn-box">
                <el-button type="primary" @click="addOrEdit(index)">添加</el-button>
                <el-button type="primary" @click="copyOrMerge(index)">合并</el-button>
              </div>-->
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyOrMergeDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="copyOrMergeSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--  合并标签  -->
    <el-dialog :close-on-click-modal="false" :visible.sync="mergeDialog.visible">
      <el-form :model="mergeDialog">
        <el-form-item label="合并标签">
          <el-input v-model="mergeDialog.toTagsName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mergeDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="mergeSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addColumnTags,
  addCategoryTags,
  editTags,
  delTags,
  mergeTags,
  copyTags
} from '@/api/section';
export default {
  name: 'Tags',
  props: ['list', 'param', 'typeEnum', 'isCategory', 'tagsBizEnumType'],
  data () {
    return {
      isCategoryTags: this.isCategory,
      listOld: this.list,
      params: this.param,
      listData: [],
      selectArr: [],
      activeLi: 0,
      checkedTags: [],
      checkedTagsInx: null,
      tagsBizEnum: this.tagsBizEnumType,

      tagsTypeEnum: this.typeEnum,
      addOrEditDialog: {
        visible: false,
        index: null,
        tagsId: null,
        tagsName: null,
        tagsInx: null,
        isAdd: null
      },
      copyOrMergeDialog: {
        visible: false,
        index: null,
        tagsId: null,
        tagsName: null,
        tagsInx: null,
        isAdd: null
      },
      mergeDialog: {
        visible: false,
        fromTagsIds: null,
        toTagsId: null,
        toTagsName: null
      },

      pTagsId: '',
      switchTagInxArr: []
    };
  },
  watch: {
    param: {
      deep: true,
      handler (data) {
        console.log('param-----data:', data);
        this.params = data;
      }
    },
    list: {
      deep: true,
      handler (data) {
        console.log('list-----data:', data);
        this.listOld = data;
        this.getFindColumnTags();
      }
    }

  },
  created () {
    this.getFindColumnTags();
  },
  methods: {
    addOrEdit (index, tag, inx) {
      console.log('index, tag, inx:', index, tag, inx);
      if (index > 0) {
        var pInx = this.switchTagInxArr[index - 1];
        this.pTagsId = this.listData[index - 1][pInx].tagsId;
      } else {
        this.pTagsId = null;
      }

      if (tag) {
        // 修改
        this.addOrEditDialog.title = '修改标签';
        this.addOrEditDialog.tagsName = tag.tagsName;
        this.addOrEditDialog.tagsId = tag.tagsId;
        this.addOrEditDialog.isAdd = false;
        this.addOrEditDialog.tagsInx = inx;
      } else {
        // 添加
        this.addOrEditDialog.title = '添加标签';
        this.addOrEditDialog.tagsName = '';
        this.addOrEditDialog.tagsId = null;
        this.addOrEditDialog.isAdd = true;
        this.addOrEditDialog.tagsInx = null;
      }

      this.addOrEditDialog.index = index;
      this.addOrEditDialog.visible = true;
    },
    copyOrMerge (index, tag, inx) {
      if (tag) {
        // 复制
        this.copyOrMergeDialog.title = '复制';
        this.copyOrMergeDialog.isCopy = true;
        this.copyOrMergeDialog.tagsId = tag.tagsId;
        this.copyOrMergeDialog.tagsName = tag.tagsName;
      } else {
        // 合并
        this.copyOrMergeDialog.title = '合并';
        this.copyOrMergeDialog.isCopy = false;
      }
      this.checkedTagsInx = null;
      this.checkedTags = [];
      this.copyOrMergeDialog.index = index;
      this.copyOrMergeDialog.visible = true;
    },
    addOrEditSubmit () {
      var params;
      if (this.addOrEditDialog.isAdd) {
        if (this.isCategoryTags) {
          // 添加分类标签
          params = {
            groupId: this.params.groupId,
            growthClassify: this.params.growthClassify || null,
            pTagsId: this.pTagsId || null,
            stageId: this.params.stageList[0] || null,
            subjectId: this.params.subjectList[0] || null,
            tagsBizEnum: this.tagsBizEnum,
            tagsName: this.addOrEditDialog.tagsName
          };
          addCategoryTags(params).then(res => {
            this.listData[this.addOrEditDialog.index].push({
              tagsId: res.data.tagsId,
              tagsName: res.data.tagsName
            });

            this.addOrEditDialog.visible = false;
            this.$message({
              message: '新增成功',
              type: 'success'
            });

            this.$emit('Callback', this.listData);
          });
        } else {
          // 添加栏目标签
          params = {
            growthClassify: this.params.growthClassify || null,
            pTagsId: this.pTagsId || null,
            stageId: this.params.stageList[0] || null,
            subjectId: this.params.subjectList[0] || null,
            tagsName: this.addOrEditDialog.tagsName
          };

          addColumnTags(params).then(res => {
            this.listData[this.addOrEditDialog.index].push({
              tagsId: res.data.tagsId,
              tagsName: res.data.tagsName
            });
            this.$emit('Callback', this.listData);
            this.addOrEditDialog.visible = false;
            this.$message({
              message: '新增成功',
              type: 'success'
            });

            this.getFindColumnTags();
          });
        }
      } else {
        params = {
          tagsId: this.addOrEditDialog.tagsId || null,
          tagsName: this.addOrEditDialog.tagsName || null,
          tagsTypeEnum: this.tagsTypeEnum
        };
        editTags(params).then(res => {
          this.listData[this.addOrEditDialog.index][
            this.addOrEditDialog.tagsInx
          ].tagsName = this.addOrEditDialog.tagsName;
          this.addOrEditDialog.visible = false;
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.getFindColumnTags();
        });
      }
    },
    copyOrMergeSubmit () {
      if (this.copyOrMergeDialog.isCopy) {
        if (this.checkedTags.length < 1) {
          this.$message.error('请选择要复制的标签目录!');
          return;
        }
        copyTags({
          fromTagsId: this.copyOrMergeDialog.tagsId,
          tagsTypeEnum: this.tagsTypeEnum,
          toTagsId: this.checkedTags[0] === '0' ? '' : this.checkedTags[0]
        }).then(res => {
          this.$message({
            message: '复制成功',
            type: 'success'
          });
          this.getFindColumnTags();
        });
      } else {
        if (this.checkedTags.length < 2) {
          this.$message.error('只允许合并同级别下的标签且不能小于两个!');
          return;
        }

        var newArr = [];
        var toArr = data => {
          data.map(item => {
            item.sub && item.sub.length > 0
              ? toArr(item.sub)
              : newArr.push(item);
          });
        };
        toArr(this.list);
        var items = newArr.filter(arr => arr.tagsId === this.checkedTags[0]);
        this.mergeDialog.toTagsName = items[0].tagsName;
        this.mergeDialog.toTagsId = items[0].tagsId;
        this.mergeDialog.fromTagsIds = this.checkedTags.slice(
          1,
          this.checkedTags.length
        );
        this.mergeDialog.visible = true;
      }
      this.copyOrMergeDialog.visible = false;
    },
    mergeSubmit () {
      mergeTags({
        fromTagsIds: this.mergeDialog.fromTagsIds,
        toTagsId: this.mergeDialog.toTagsId,
        toTagsName: this.mergeDialog.toTagsName,
        tagsTypeEnum: this.tagsTypeEnum
      }).then(res => {
        this.$message({
          message: '合并成功',
          type: 'success'
        });
        this.getFindColumnTags();
      });
    },
    tagsChange (value, index) {
      if (!this.copyOrMergeDialog.isCopy) {
        if (
          this.checkedTagsInx !== index &&
          this.checkedTagsInx !== '' &&
          this.checkedTagsInx !== null
        ) {
          this.$message({
            message: '只允许合并同级别下的标签且不能小于两个!',
            type: 'warning'
          });
          this.checkedTags.shift();
        }
        this.checkedTagsInx = index;

        if (value && value.length <= 0) {
          this.checkedTagsInx = null;
        }
      }
    },

    delect (index, tag, inx) {
      const msg = '确认是否删除该标签！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delTags({
            tagsId: tag.tagsId
          }).then(res => {
            this.listData[index].splice(inx, 1);
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          });
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },

    // 标签切换
    switchTag (index, tagItem, tagInx) {
      console.log('tagItem:', tagItem);
      this.switchTagInxArr[index] = tagInx;

      this.activeLi = tagInx;
      this.listData.splice(index + 1, this.listData.length - 1);
      this.selectArr.splice(index, this.selectArr.length - 1);

      if (tagItem.sub && tagItem.sub.length > 0) {
        var sub = [];
        for (var i in tagItem.sub) {
          sub.push(tagItem.sub[i]);
        }
        this.listData.splice(index + 1, 1, sub);
      } else {
        this.listData.splice(index + 1, 1, [{}]);
      }
      this.selectArr.splice(index, 1, tagInx);
    },

    getFindColumnTags () {
      this.listData = [];
      var sub = [];
      console.log(this.listOld);
      if (this.listOld.length > 0) {
        for (var i in this.listOld) {
          sub.push(this.listOld[i]);
        }
      } else {
        sub = [{}];
      }
      this.listData.push(sub);
      // this.selectArr.push(this.activeLi);

      // this.switchTag(0, this.listData[0][this.activeLi], this.activeLi);
    }
  }
};
</script>

<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 10px;
}
.tags-box {
  height: 240px;
  overflow-y: auto;
  .tags-item {
    display: flex;
    padding: 0 10px;
    cursor: pointer;
    .checkbox {
    }
    .name {
      flex: 1;
    }
    .text-box {
      width: 130px;
      text-align: center;
    }
  }
  li.active {
    background: #c0d8fb;
  }
}
.btn-box {
  display: flex;
  .el-button {
    flex: 1;
  }
}
</style>
